<template>
  <div>
    <el-drawer
      v-model="showSecurityIssues"
      title="修改密码"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="editForm"
        :rules="rules"
        size="large"
        label-width="100px"
        label-position="left"
      >
        <el-form-item prop="password">
          <template #label>
            <p class="edit-form-label">原密码</p>
          </template>
          <el-input type="password" v-model="editForm.password" clearable />
        </el-form-item>
        <el-form-item prop="new_password" class="new-password">
          <template #label>
            <p class="edit-form-label">新密码</p>
          </template>
          <el-input type="password" v-model="editForm.new_password" clearable @focus="showPopup = true" @input="validateNewPass" />
          <!-- 新密码的规则弹框 -->
          <transition name="slide-fade">
            <div class="warn-popup" v-show="showPopup">
              <div class="warn-triangle"></div>
              <div class="warn-triangle2"></div>
              <div class="warn-content">
                <ul>
                  <li>
                    <i class="iconfont correct" v-show="warnNewFlag.inputLength">&#xe693;</i>
                    <i class="iconfont error" v-show="!warnNewFlag.inputLength">&#xe695;</i>
                    <span>长度为8~20位字符</span>
                  </li>
                  <li>
                    <i class="iconfont correct" v-show="warnNewFlag.inputType">&#xe693;</i>
                    <i class="iconfont error" v-show="!warnNewFlag.inputType">&#xe695;</i>
                    <span>只能包含英文大小写字母、数字与标点符号（除空格）</span>
                  </li>
                  <li>
                    <i class="iconfont correct" v-show="warnNewFlag.typeofNumber">&#xe693;</i>
                    <i class="iconfont error" v-show="!warnNewFlag.typeofNumber">&#xe695;</i>
                    <span>英文大小写字母、数字与标点符号至少包含两种</span>
                  </li>
                </ul>
              </div>
            </div>
          </transition>
        </el-form-item>
        <el-form-item prop="confirm_new_password">
          <template #label>
            <p class="edit-form-label">确认新密码</p>
          </template>
          <el-input type="password" v-model="editForm.confirm_new_password" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { computed, ref, reactive } from 'vue'
import { userEditPassword } from "@/api/user"
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const store = useStore()
const router = useRouter()

const props = defineProps({
  showDrawer: {
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits(['update:showDrawer'])
const showSecurityIssues = computed(()=>{return props.showDrawer})

// 修改密码
const ruleFormRef = ref()
const editForm = reactive({
  password: '',
  new_password: '',
  confirm_new_password: '',
})
// 获得焦点展示校验弹框
const showPopup = ref(false)
// 是否新密码达到输入条件的标识
const warnNewFlag = reactive({
  inputLength: false,
  inputType: false,
  typeofNumber: false
})
// 新密码失去焦点触发的函数
const loseNewPassFocus = (rule, value, callback) => {
  // 关闭规则弹框
  showPopup.value = false
  // 判断输入的新密码是否已经全部达到规则的要求
  if (warnNewFlag.inputLength && warnNewFlag.inputType && warnNewFlag.typeofNumber) {
    callback()
  } else {
    callback(new Error('请按要求填写密码'))
  }
}
// 校验新密码的回调函数
const validateNewPass = (value) => {
  if (value) {
    // 判断是否长度在8~20之间
    if (value.length >= 8 && value.length <= 20) {
      warnNewFlag.inputLength = true
    } else {
      warnNewFlag.inputLength = false
    }
    // 判断是否除英文大小写字母、数字、标点符号（除空格）以外的字符
    if (/\s/g.test(value)) {
      warnNewFlag.inputType = false
    } else {
      warnNewFlag.inputType = true
    }
    // 判断是否包含两种符号
    var pwdCount = 0; // 统计密码包含了几种字符
    var pwdRegex1 = new RegExp('(?=.*[0-9])'); // 纯数字
    var pwdRegex2 = new RegExp('(?=.*[a-zA-Z])'); // 小写字母
    var pwdRegex3 = new RegExp('(?=.*[^a-zA-Z0-9])'); // 特殊字符
    if (pwdRegex1.test(value)) {
      pwdCount = pwdCount + 1
    }
    if (pwdRegex2.test(value)) {
      pwdCount = pwdCount + 1
    }
    if (pwdRegex3.test(value)) {
      pwdCount = pwdCount + 1
    }
    if (pwdCount < 2) {
      warnNewFlag.typeofNumber = false
    } else {
      warnNewFlag.typeofNumber = true
    }
  } else {
    warnNewFlag.inputLength = false
    warnNewFlag.inputType = false
    warnNewFlag.typeofNumber = false
  }
}
// 校验确认新密码的回调函数
const validateConfirmNewPass = (rule, value, callback) => {
  if (editForm.new_password === value) {
    callback()
  } else {
    callback(new Error('密码输入不一致，请重新输入'))
  }
}
// 原密码校验规则
const validateOriginalPass = (rule, value, callback) => {
  if (editForm.password !== '') {
    callback()
  } else {
    callback(new Error('请输入原密码'))
  }
}
// 校验规则
const rules = reactive({
  password: [{validator: validateOriginalPass, trigger: 'blur'}],
  new_password: [{ validator: loseNewPassFocus, trigger: 'blur' }],
  confirm_new_password: [{ validator: validateConfirmNewPass, trigger: 'blur' }],
})
// 提交修改密码
const showEditPassDialog = ref(false)
const confirmClick = (formEl) => {
  if(!formEl) return
  formEl.validate((valid) => {
    if(valid){
      let _editForm = (({password, new_password}) => ({password, new_password}))(editForm)
      console.log(_editForm)
      userEditPassword(_editForm).then(() => {
        showEditPassDialog.value = false
        ElMessage({
          showClose: true,
          message: '修改成功,正在跳转登录',
          type: 'success',
        })
        store.dispatch('user/logout').then(() => {
          router.push('/login')
        })
        emits('update:showDrawer',false)
      })
    }
  })
}

const handleClose = () => {
  emits('update:showDrawer',false)
}
const cancelClick = () => {
  emits('update:showDrawer',false)
}
</script>
<style scoped lang='scss'>
.el-select{
  width: 100%;
}
</style>